package com.zkyc.framework.schedulejob.task;


import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkyc.framework.common.constant.NumberConstant;
import com.zkyc.framework.common.mapper.CodeComparisonMapper;
import com.zkyc.framework.common.mapper.CodeOrganiationMapper;
import com.zkyc.framework.common.mapper.PostMapper;
import com.zkyc.framework.common.pojo.CodeComparison;
import com.zkyc.framework.common.pojo.CodeOrganiation;
import com.zkyc.framework.common.pojo.Post;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.HashSet;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * @description 定时更新访客量
 */
@Slf4j
@Component
public class PostTask {
    @Autowired
    PostMapper postMapper;

    @Autowired
    CodeComparisonMapper codeComparisonMapper;

    @Autowired
    CodeOrganiationMapper codeOrganiationMapper;

    //3.0突然调不通
    //public static final String GET_TOKEN = "http://talents.zhejianglab.com:8200/wt/api/3.0/getToken";
    //缺少字段
    //public static final String GET_POSITION = "http://talents.zhejianglab.com:8200/wt/api/3.0/auth/position/getPositionInformation";
    public static final String GET_TOKEN = "http://postdoctor-talents.zhejianglab.com:8200/apiserver/api/2.0/getToken";
    public static final String GET_POSITION = "http://postdoctor-talents.zhejianglab.com:8200/apiserver/api/2.0/auth/getPostInfo/getPositionsInfo";
    public static final String POST_DOCTOR = "0/1227/37850543";


    /**
     * 每四小时同步一次
     */
    @Scheduled(cron = "0 0 0/1 * * ?")
    //@Scheduled(cron = "*/5 * * * * ?")
    public void process() {
        //1.获取token
        JSONObject login = new JSONObject();
        login.put("corpCode", "zhejianglab");//用户名
        login.put("userName", "zhejianglab");//密码
        login.put("password", "8875AE815E2F8FA7D950166CFD4D0962");
        String tokenJson = HttpRequest.post(GET_TOKEN)
                .body(login.toJSONString())
                .execute().body();
        String token = JSONObject.parseObject(JSONObject.parseObject(tokenJson).get("data").toString()).get("token").toString();

        //2.获取信息
        JSONObject params = new JSONObject();
        params.put("currentPage", 1);
        params.put("rowSize", 1000);
        params.put("recruitType", 2);
        params.put("postStatus", 5);
        params.put("customModules","workplace_Name");
        // 中文
        // params.put("languages", 1);
        String informationJson = HttpRequest.post(GET_POSITION)
                .header("Authorization", "Bearer " + token)
                .body(params.toJSONString())
                .execute().body();
        JSONArray jsonChineseArr = JSONObject.parseObject(informationJson).getJSONArray("data");
        // 英文
        /*params.put("languages", 2);
        String eInformationJson = HttpRequest.post(GET_POSITION)
                .header("Authorization", "Bearer " + token)
                .body(params.toJSONString())
                .execute().body();
        JSONArray jsonEnglishArr = JSONObject.parseObject(eInformationJson).getJSONArray("data");*/
        //存储拉取下来的postId
        HashSet<Integer> setA = new HashSet<>();
        //存储数据库中现有的postId
        HashSet<Integer> setB = postMapper.getAllId();
        for (int i = 0; i < jsonChineseArr.size(); i++) {
            try {
                Post post = new Post();
                JSONObject jsonObject = jsonChineseArr.getJSONObject(i);
                //不是博士后就过滤掉
                if (!POST_DOCTOR.equals(jsonObject.getOrDefault("postType", " ").toString())) continue;
                //获取id
                post.setId(Integer.parseInt(jsonObject.getOrDefault("postId", " ").toString()));
                //职位名称
                post.setPostName(jsonObject.getOrDefault("postNameCh", " ").toString());
                Pattern pattern = Pattern.compile("[\u4e00-\u9fa5]");
                Matcher matcher = pattern.matcher(post.getPostName());
                if (matcher.find()) {
                    post.setLanguages(NumberConstant.NUMBER_1);
                } else {
                    post.setLanguages(NumberConstant.NUMBER_2);
                }
                //工作地点
                String workplaceByGet = jsonObject.getOrDefault("workplace", " ").toString();
                StringBuilder workPlace = new StringBuilder();
                String[] split = workplaceByGet.split(",");
                for (String s : split) {
                    if (s.split("/").length == 5){
                        s = s.substring(0,s.lastIndexOf("/")) ;
                    }
                    QueryWrapper<CodeComparison> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code",s);
                    CodeComparison codeComparison = codeComparisonMapper.selectOne(queryWrapper);
                    workPlace.append(codeComparison.getChineseName()).append(",");
                }
                workPlace = new StringBuilder(workPlace.substring(0, workPlace.length() - 1));
                post.setPlace(workPlace.toString());
                //录用人数
                post.setRecruitingNumber(jsonObject.getOrDefault("recruitNum", " ").toString());
                //机构名称
                String orgId = jsonObject.getOrDefault("orgId", " ").toString();
                CodeOrganiation codeOrganiation = codeOrganiationMapper.selectById(orgId);
                post.setResearchCenter(codeOrganiation.getChineseName());
                CodeOrganiation codeOrganization = codeOrganiationMapper.selectById(codeOrganiation.getPid());
                if (codeOrganization != null) {
                    post.setResearchInstitute(codeOrganization.getChineseName());
                }
                //发布时间
                String publishDate = jsonObject.getOrDefault("publishDate", " ").toString();
                post.setPublishDate(new Date(new Long(publishDate)));
                //任职要求
                JSONArray jsonArray = jsonObject.getJSONArray("positionDetail");
                if (jsonArray != null && jsonArray.size() != 0) {
                    JSONObject positionDetail = jsonArray.getJSONObject(0);
                    if (positionDetail != null) {
                        Object orDefault = positionDetail.getOrDefault("serviceCondition", " ");
                        post.setRequest(orDefault.toString());
                    }
                }

                post.setPostUrl("https://talents.zhejianglab.com/wt/zhejianglab/web/index#/pd/positionDetail=1&PostId=" + post.getId() + "&RecruitType=2");
                //
                setA.add(post.getId());
                Post post1 = postMapper.selectById(post.getId());
                if (post1 == null) {
                    postMapper.insert(post);
                    //System.out.println("插入成功");
                } else {
                    postMapper.updateById(post);
                    //System.out.println("更新成功");
                }
            } catch (Exception e) {
                log.error("插入招聘信息出错" , e);
            }
        }
        /*for (int i = 0; i < jsonEnglishArr.size(); i++) {
            try {
                Post post = new Post();
                post.setLanguages(NumberConstant.NUMBER_2);
                JSONObject jsonObject = jsonEnglishArr.getJSONObject(i);
                //不是博士后就过滤掉
                if (!POST_DOCTOR.equals(jsonObject.getOrDefault("postType", " ").toString())) continue;
                //获取id
                post.setId(Integer.parseInt(jsonObject.getOrDefault("postId", " ").toString()));
                //职位名称
                post.setPostName(jsonObject.getOrDefault("postNameCh", " ").toString());
                //工作地点
                String workplaceByGet = jsonObject.getOrDefault("workplace", " ").toString();
                StringBuilder workPlace = new StringBuilder();
                String[] split = workplaceByGet.split(",");
                for (String s : split) {
                    if (s.split("/").length == 5){
                        s = s.substring(0,s.lastIndexOf("/")) ;
                    }
                    QueryWrapper<CodeComparison> queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("code",s);
                    CodeComparison codeComparison = codeComparisonMapper.selectOne(queryWrapper);
                    workPlace.append(codeComparison.getChineseName()).append(",");
                }
                workPlace = new StringBuilder(workPlace.substring(0, workPlace.length() - 1));
                post.setPlace(workPlace.toString());
                //录用人数
                post.setRecruitingNumber(jsonObject.getOrDefault("recruitNum", " ").toString());
                //机构名称
                String orgId = jsonObject.getOrDefault("orgId", " ").toString();
                CodeOrganiation codeOrganiation = codeOrganiationMapper.selectById(orgId);
                post.setResearchCenter(codeOrganiation.getChineseName());
                post.setResearchInstitute(codeOrganiationMapper.selectById(codeOrganiation.getPid()).getChineseName());
                //发布时间
                String publishDate = jsonObject.getOrDefault("publishDate", " ").toString();
                post.setPublishDate(new Date(new Long(publishDate)));
                //任职要求
                //post.setRequest(jsonObject.getJSONArray("positionDetail").getJSONObject(0).getOrDefault("serviceCondition", " ").toString());

                post.setPostUrl("https://talents.zhejianglab.com/wt/zhejianglab/web/index#/pd/positionDetail=1&PostId=" + post.getId() + "&RecruitType=2");
                //
                setA.add(post.getId());
                Post post1 = postMapper.selectById(post.getId());
                if (post1 == null) {
                    postMapper.insert(post);
                    //System.out.println("插入成功");
                } else {
                    postMapper.updateById(post);
                    //System.out.println("更新成功");
                }
            } catch (Exception e) {
                log.error("插入英文招聘信息出错" + e);
            }
        }*/
        //用于存放结果
        HashSet<Integer> resSet = new HashSet<>(setB);
        //找到差集
        resSet.removeAll(setA);
        if (!resSet.isEmpty()){
            postMapper.deleteBatchIds(resSet);
            System.out.println("删除了" + resSet);
        }
    }
}
